<?php
namespace StarCloud\Library;

use Framework\Library\Tool;
use Phalcon\Mvc\Collection;

class Config extends \Phalcon\Config
{
    public function offsetExists($index) : bool
    {
        return !is_null($this->offsetGet($index));
    }

    public function offsetGet($index)
    {
        if (!parent::offsetExists($index)) {
            if (file_exists($filePath = ACM_CONFIG_PATH . DS . lcfirst($index) . '.php')) {
                $indexConfigArray = Tool::getConfig(ACM_CONFIG_PATH, $index);
            } else {
                if (!defined('APPLICATION_CONFIG_PATH') || empty($indexConfigArray = Tool::getConfig(APPLICATION_CONFIG_PATH, $index))) {
                    $indexConfigArray = Tool::getConfig(PLATFORM_CONFIG_PATH, $index);
                }
            }

            $this->merge(new \Phalcon\Config([$index => $indexConfigArray]));
        }

        if (is_object($result = parent::offsetGet($index))) {
            return $result->toArray();
        } else {
            return $result;
        }
    }

    public function writeConfigToPhpFile(string $fileName, array $value)
    {
        $content = implode("\r\n", [
            "<?php",
            "return",
            var_export($value, true) . ';'
        ]);

        file_put_contents($fileName, $content);
    }
}
